/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.repository.utils;

import cn.ac.nercis.pes.common.utils.DataUtils;
import cn.ac.nercis.pes.repository.constant.BaseConstants;
import cn.ac.nercis.pes.repository.model.base.BaseEntity;
import lombok.NonNull;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * 数据库辅助类
 * @author zpy
 * @version 1.0.0
 */
public final class DbUtils {
    private DbUtils(){}

    /**
     * 获取重复数据
     * @param data 数据列表
     * @return 返回重复的数据
     * @param <T> 实体信息列表
     */
    public static <T extends BaseEntity> List<T> findDuplicateData(List<T> data){
        if(data.size() < BaseConstants.DUPLICATE_DATA_COUNT){
            return Collections.emptyList();
        }
        List<T> duplicateData = new ArrayList<>();
        T afterItem = null;
        for(T item:data){
            if(Objects.isNull(afterItem)){
                afterItem = item;
                continue;
            }
            if(DataUtils.compareDateIsBefore(getModifyDate(item),getModifyDate(afterItem))){
                duplicateData.add(item);
            }else{
                duplicateData.add(afterItem);
                afterItem = item;
            }
        }
        return duplicateData;
    }

    /**
     * 获取数据变更时间
     * @param entity 实体信息
     * @return 数据变更时间
     */
    public static <T extends BaseEntity> LocalDateTime getModifyDate(@NonNull T entity){
        return Objects.nonNull(entity.getModifyTime()) ? entity.getModifyTime() : entity.getCreateTime();
    }

}